package com.zhisland.base.support.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class PinYinUtil {

	private static HanyuPinyinOutputFormat pinYinFormat;
	
	static{
		if(pinYinFormat==null){
			pinYinFormat = new HanyuPinyinOutputFormat();
			pinYinFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
			pinYinFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
			pinYinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		}
	}
	
	public static String hanYuToPinYinAll (String chinese) throws Exception{
		char[] chs = chinese.toCharArray();
		StringBuffer sb = new StringBuffer();
		
		for (char c : chs) {
			if((c>='\u4E00'&&c<='\u9FA5')||( c>='\uF900'&&c<='\uFA2D')){
				String[] strs = PinyinHelper.toHanyuPinyinStringArray(c, pinYinFormat);
				if(strs!=null&&strs.length>0){
					sb.append(strs[0]);
				}else{
					throw new Exception(c + " not have pinYin");
				}
			}else{
				sb.append(c);
			}
		}
		return sb.toString();
	}
	
	public static String hanYuToPinYinFirst (String chinese) throws Exception{
		char[] chs = chinese.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (char c : chs) {
			if((c>='\u4E00'&&c<='\u9FA5')||( c>='\uF900'&&c<='\uFA2D')){
				String[] strs = PinyinHelper.toHanyuPinyinStringArray(c, pinYinFormat);
				if(strs.length>0){
					sb.append(strs[0].charAt(0));
				}else{
					throw new Exception(c + " not have pinYin");
				}
			}else{
				sb.append(c);
			}
		}
		return sb.toString();
	}
	
	public static String hanYuToPinYinFirstEnOrNumOnly(String chinese) throws Exception{
		String str = hanYuToPinYinFirst(chinese);
		char[] chs = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (char c : chs) {
			if(Character.isLetterOrDigit(c)){
				sb.append(c);
			}
		}
		return sb.toString();
	}
}
